import {useMicVAD,utils} from "@ricky0123/vad-react"
import React, {useEffect, useState} from "react"
import { List } from 'antd';


 function MicrophoneVoiceActivityDetector () {

     const [audioData,setAudioDataData]=useState([])



     const vad = useMicVAD({
         onSpeechEnd: (audio) => {
             const wavBuffer = utils.encodeWAV(audio)

             const base64 = utils.arrayBufferToBase64(wavBuffer)
             const url = `data:audio/wav;base64,${base64}`
             setAudioDataData(currentUrls => [...currentUrls, url])

             const audioBlob = new Blob([wavBuffer], { type: "audio/wav" });
             const audioFile = new File([audioBlob], "recording.wav", { type: "audio/wav" });
             const formData = new FormData();
             formData.append("files", audioFile); // 将音频文件添加到 FormData 中
             return new Promise((resolve, reject) => {
                 fetch(`api/speech-to-speech/voice/upload`, {
                     method: "post",
                     body: formData
                     // mode: "no-cors"
                 })
                     .then((res) => res.json())
                     .then((res) => {
                         resolve({
                             default: `${res.data[0]}`
                         });
                     })
                     .catch((err) => {
                         reject(err);
                     });
             })

         },
     })
     useEffect(()=>{

         vad.start()
     },[])

    return (<>
            <div>{vad.userSpeaking && "用户正在说话"}</div>
            <List
                size="large"
                header={<div>已录语音</div>}

                bordered
                dataSource={audioData}
                renderItem={item => <List.Item>
                    <audio  controls={true} src={item}></audio>
                </List.Item>}
            />
        </>


    )
 }

export default MicrophoneVoiceActivityDetector